package com.bbx.taxi.client.Activity.Address;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.animation.LayoutTransition;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.comm.returns.line.Cities;
import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.MyApplication.EventHandler;
import com.bbx.taxi.client.MyApplication.OnLocationResultListener;
import com.bbx.taxi.client.Util.Cn2Spell;
import com.bbx.taxi.client.Util.ToCity;
import com.bbx.taxi.client.widget.Drag.CityDragLayout;
import com.bbx.taxi.client.widget.Drag.CityDragLayout.OnCityDragViewStatusListener;
import com.bbx.taxi.client.widget.Drag.DragLayout;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Base.BaseMapBBXActivity;
import com.bbx.taxi.client.Adapter.EditAddressAdapter;
import com.bbx.taxi.client.Bean.City;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.ChangeAttribute;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.AddressMsg;
import com.bbx.taxi.client.DB.AddressDB;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.example.loadview.LoadingDialog;

/**
 * 编辑地址，定位地址
 */
public class EditAddressActivity extends BaseMapBBXActivity implements
		OnClickListener, OnItemClickListener, OnGetPoiSearchResultListener,
		OnGetGeoCoderResultListener, TextWatcher, OnLocationResultListener,
		OnCityDragViewStatusListener {
	@InjectView(R.id.layout_nodata)
	LinearLayout layout_nodata;
	@InjectView(R.id.layout_city_search)
	RelativeLayout layout_city_search;
	@InjectView(R.id.et_city)
	EditText et_city;
	@InjectView(R.id.listview)
	ListView listview;
	@InjectView(R.id.et_edit)
	EditText et_edit;
	@InjectView(R.id.layout_city)
	LinearLayout layout_city;
	@InjectView(R.id.tv_city)
	TextView tv_city;
	@InjectView(R.id.tv_city_jiantou)
	ImageView tv_city_jiantou;
	@InjectView(R.id.tv_loading)
	TextView tv_loading;
	@InjectView(R.id.bmapView)
	MapView mMapView;
	@InjectView(R.id.iv_delete)
	ImageView iv_delete;
	@InjectView(R.id.iv_city_delete)
	ImageView iv_city_delete;
	@InjectView(R.id.tv_myposition)
	TextView tv_myposition;
	@InjectView(R.id.icon_mapid)
	ImageView icon_mapid;
	/** 切换城市提示 */
	@InjectView(R.id.layout_switch_city)
	LinearLayout layout_switch_city;
	@InjectView(R.id.iv_locate)
	ImageView iv_locate;
	@InjectView(R.id.citydragLayout)
	public CityDragLayout citydragLayout;
	@InjectView(R.id.layout_map)
	RelativeLayout layout_map;
	@InjectView(R.id.map_view)
	View map_view;
	@InjectView(R.id.layout_listview)
	LinearLayout layout_listview;
	@InjectView(R.id.tv_cancel)
	TextView tv_cancel;
	public final static int TYPE_GEOCODER = 0;
	public final static int TYPE_SEARCH = 1;
	public final static int TYPE_COLLECT = 3;
	public int type = TYPE_GEOCODER;
	public final static int MSG_SELETE_CITY = 0;
	private BaiduMap mBaiduMap;
	boolean isFirstLoc = true;// 是否首次定位
	public LocationClient mLocClient;
	private PoiSearch mPoiSearch = null;
	private GeoCoder mSearch = null; // 地理编码
	private ReverseGeoCodeResult myposition;// 我的位置
	/** 搜索结果列表 */
	private List<PoiInfo> list_key;
	/** 地理编码列表 */
	private List<PoiInfo> list_geo;
	/** 收藏地址跟历史地址 */
	private List<Map<String, String>> list_collect;
	List<City> cityList = new ArrayList<City>();
	private EditAddressAdapter mMyAdapter_geocoder;// 地面编码
	private EditAddressAdapter mMyAdapter_search;// 搜索结果
	private EditAddressAdapter mMyAdapter_collect;// 收藏跟历史
	private double latitude;
	private double longitude;
	private AddressDB db_address;
	private int intentType;
	/**当点击途经点的时候的id*/
	private int point_id;
	private boolean isInCity = false;// 判断是否是市内用车
	private boolean isInKJ = false;// 判断是否是快件
	private boolean isOpend = false;// 是否有开通
	private LineDB db_line;// 线路数据库
	private LoadingDialog dialog;
	/** 判断是否设置定位城市 */
	private boolean isLocationCity = true;
	private String is_detail = Value.CITY_NODETAIL;
	/** 传递到Handler用的分隔符 */
	private String split = "%#";
	private String address_name;
	private Intent intent;
	List<String> list_incity_num;
	List<String> list_incity_cn;

	protected void onCreate(Bundle savedInstanceState) {
		showTitle(false);
		setContentView(R.layout.editaddress);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initView() {
		layout_base.setBackgroundColor(getResources().getColor(R.color.white));
		citydragLayout.setOnCityDragViewStatusListener(this);
//		listview.setEmptyView(layout_nodata);
//		setTitle(getString(R.string.edit_address));
		intent = getIntent();
		isInCity = intent.getExtras().getBoolean(AddressMsg.extra_incity);
		isInKJ = intent.getExtras().getBoolean(AddressMsg.extra_inkj);
		isOpend = intent.getExtras().getBoolean(AddressMsg.extra_cityopend);
		dialog = new LoadingDialog(context);
		db_line = new LineDB(this);
		db_address = new AddressDB(this);
		list_key = new ArrayList<PoiInfo>();
		list_geo = new ArrayList<PoiInfo>();
		list_collect = new ArrayList<Map<String, String>>();
		if (isInCity) {
			String str_incity_cn = SharedPreUtil.getStringValue(this,
					SharedPreEncryptUtil.list_incity_cn, "");
			list_incity_cn = Arrays.asList(str_incity_cn.replace("[", "")
					.replace("]", "").trim().split(","));
		}

		mMyAdapter_geocoder = new EditAddressAdapter(this, list_geo,
				EditAddressAdapter.TYPE_GEOCODER);
		mMyAdapter_search = new EditAddressAdapter(this, list_key,
				EditAddressAdapter.TYPE_SEARCH);
		mMyAdapter_collect = new EditAddressAdapter(this, list_collect,
				EditAddressAdapter.TYPE_COLLECT, db_address);
		listview.setAdapter(mMyAdapter_geocoder);

		listview.setOnItemClickListener(this);
		tv_myposition.setOnClickListener(this);
		layout_city.setOnClickListener(this);
		tv_cancel.setOnClickListener(this);
		et_edit.addTextChangedListener(this);
		et_edit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus && layout_city.getVisibility() != View.GONE) {
					if (tv_city.getText().toString() != null
							&& !tv_city.getText().toString().equals("")
							&& !tv_city.getText().toString()
									.equals(getString(R.string.default_city))
							&& !tv_city.getText().toString().equals("null")) {
						hideCity();
					} else {
						setEditTextCityFocusable();
						if (!isInCity) {
							ToastUtil.showToast(context, R.string.choice_city);
						}
					}
				}
			}
		});
		iv_delete.setOnClickListener(this);
		iv_city_delete.setOnClickListener(this);
		et_edit.setOnClickListener(this);
		iv_locate.setOnClickListener(this);
		mPoiSearch = PoiSearch.newInstance();
		mPoiSearch.setOnGetPoiSearchResultListener(this);
		// 初始化搜索模块，注册事件监听
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		point_id=intent.getExtras().getInt(AddressMsg.extra_point_id);
		intentType = intent.getExtras().getInt(AddressMsg.extra_editaddress);
		switch (intentType) {
		case AddressMsg.ADDRESS_START_MAIN:
		case AddressMsg.ADDRESS_START_CHANGE:
			et_edit.setFocusable(false);
			// 设置hint
			if (isInKJ) {
				// tv_edit.setHint(R.string.hint_start_kj);
				et_edit.setHint(R.string.hint_start_kj);
			} else {
				// tv_edit.setHint(R.string.hint_start);
				et_edit.setHint(R.string.hint_start);
			}
//			setTitle(getString(R.string.start_address));
			ToCity.setLocalCityList(this);
			address_name = "";
			if (mApplication.loctionCity != null
					&& !mApplication.loctionCity.equals("")) {
				tv_city.setText(mApplication.loctionCity);
			}
			readAllDB_address();
			if (isInCity && !list_incity_cn.isEmpty()) {
				tv_city_jiantou.setVisibility(View.GONE);
			}
			// 定位失败，则不显示地图
			if (isNoCity()) {
				type=TYPE_COLLECT;
				showEditText(false);
				showCity();
			} else {
				type=TYPE_GEOCODER;
				hideEditText();
				hideCity();
				et_edit.setFocusable(false);
				et_city.setFocusable(false);
				hideInput();
				mApplication.setOnLocationResultListener(this);
				latitude = mApplication.latitude;
				longitude = mApplication.longitude;
				initmap();
				if (latitude != 0 && longitude != 0) {
					onGeoCoder(latitude, longitude);
				} else {
					mApplication.onStartLocation();
				}
				
			}

			break;
		case AddressMsg.ADDRESS_END_MAIN:
		case AddressMsg.ADDRESS_POINT:
			type=TYPE_COLLECT;
			showEditText(false);
			if (mApplication.loctionCity == null
					|| mApplication.loctionCity.equals("")
					|| mApplication.loctionCity.equals("null")) {
				showCity();
			} else {
				tv_city.setText(mApplication.loctionCity);
				hideCity();
			}
			readAllDB_address();
			// 设置hint
			if (isInKJ) {
				// tv_edit.setHint(R.string.hint_end_kj);
				et_edit.setHint(R.string.hint_end_kj);
			} else {
				// tv_edit.setHint(R.string.hint_end);
				et_edit.setHint(R.string.hint_end);
			}
//			setTitle(getString(R.string.end_address));
			MainAttribute main = MainAttribute.getInstance();
			if (main.getStartCity(isInCity).equals("")) {
				ToCity.setLocalCityList(this);
				address_name = "";
			} else {
				if (isInCity && !list_incity_cn.isEmpty()) {
					if (isCityInformation(main.getStartCity(isInCity))) {
						Message msg = new Message();
						msg.what = MSG_SELETE_CITY;
						msg.obj = main.getStartCity(isInCity) + split
								+ is_detail;
						mHandler.sendMessage(msg);
						tv_city_jiantou.setVisibility(View.GONE);
					}

				} else {
					ToCity.setLocalCityList(this);
				}
				address_name = main.getStartCity(isInCity);
			}
			break;
		case AddressMsg.ADDRESS_END_CHANGE:
			// 设置hint
			if (isInKJ) {
				// tv_edit.setHint(R.string.hint_end_kj);
				et_edit.setHint(R.string.hint_end_kj);
			} else {
				// tv_edit.setHint(R.string.hint_end);
				et_edit.setHint(R.string.hint_end);
			}
//			setTitle(getString(R.string.end_address));
			ChangeAttribute change = ChangeAttribute.getInstance();
			if (change.getStartCity().equals("")) {
				ToCity.setLocalCityList(this);
				address_name = "";
			} else {
				if (isInCity && !list_incity_cn.isEmpty()) {
					if (isCityInformation(change.getStartCity())) {
						Message msg = new Message();
						msg.what = MSG_SELETE_CITY;
						msg.obj = change.getStartCity() + split + is_detail;
						mHandler.sendMessage(msg);
						tv_city_jiantou.setVisibility(View.GONE);
					}
				} else {
					ToCity.setLocalCityList(this);
				}
				address_name = change.getStartCity();
			}
			showEditText(false);
			showCity();
			readAllDB_address();
			break;
		case AddressMsg.ADDRESS_COLLECT:
			showEditText(false);
			readAllDB_address();
			break;
		}
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void desotryItems() {

	}

	public void initmap() {
		mMapView.setVisibility(View.VISIBLE);
		icon_mapid.setVisibility(View.VISIBLE);
		iv_locate.setVisibility(View.VISIBLE);
		// 如果不是出发地，则不定位
		if (intentType != AddressMsg.ADDRESS_START_MAIN
				&& intentType != AddressMsg.ADDRESS_START_CHANGE) {
			return;
		}
		mBaiduMap = mMapView.getMap();
		MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(16);
		mBaiduMap.animateMapStatus(u);
		if (mBaiduMap != null) {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					mBaiduMap
							.setMyLocationConfigeration(new MyLocationConfiguration(
									LocationMode.NORMAL,
									true,
									BitmapDescriptorFactory
											.fromResource(R.drawable.icon_mapid2)));
				}
			}, 100);
			mBaiduMap.setMyLocationEnabled(true);
			mBaiduMap
					.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {//

						@Override
						public void onMapStatusChangeStart(MapStatus mapStatus) {
							tv_myposition
									.setText(getString(R.string.my_location));
							tv_myposition.setVisibility(View.GONE);
							myposition = null;

						}

						@Override
						public void onMapStatusChangeFinish(MapStatus mapStatus) {
							tv_loading.setVisibility(View.VISIBLE);
							tv_loading.setText(getString(R.string.tv_loading));
							onGeoCoder(mapStatus.target.latitude,
									mapStatus.target.longitude);
						}

						@Override
						public void onMapStatusChange(MapStatus mapStatus) {
							// TODO Auto-generated method stub

						}
					});
		}

	}

	/**
	 * 读取所有数据
	 */
	public void readAllDB_address() {
		if (list_collect != null)
			list_collect.clear();
		readAllDB_collect(Value.ADDRESS_TYPE_COLLECTE, tv_city.getText()
				.toString());
	}

	/**
	 * 读取所有数据,先收藏后历史
	 */
	public void readAllDB_collect(String isCollection, String cityname) {
		list_collect.addAll(db_address.readAllDB(this, isCollection, cityname));
		if (isCollection.equals(Value.ADDRESS_TYPE_COLLECTE)) {
			readAllDB_collect(Value.ADDRESS_TYPE_HISTORY, cityname);
		}
		if(type==TYPE_COLLECT){
		   notifyDataSetChanged(mMyAdapter_collect);
		}
	}

	/**
	 * 地理编码搜索
	 */
	public void onGeoCoder(double latitude, double longitude) {
		if(type == TYPE_GEOCODER){
		LatLng ptCenter = new LatLng(latitude, longitude);
		// 反Geo搜索
		mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
		}
	}

	/**
	 * 城市关键字搜索,search==true的时候无论是否有值，都要搜索【用于具体信息，如厦门北站这类信息】，false的时候，则根据有值才搜索
	 */
	public void onCityKeySearch(String key, boolean search) {
		if ((key != null && !key.equals("")) || search) {
			PoiCitySearchOption info = new PoiCitySearchOption();
			info.city(tv_city.getText().toString());
			info.pageCapacity(50);
			info.keyword(tv_city.getText().toString() + key);
			mPoiSearch.searchInCity(info);
		}
	}

	public void initDefaultLocation(BDLocation location) {

		if (location != null) {// 先默认定位
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}
	}

	public void initDefaultLocation(ReverseGeoCodeResult result) {
		//
		// if (result != null) {// 先默认定位
		// MyLocationData locData = new MyLocationData.Builder()
		// .accuracy(result.getAddressDetail()..getRadius())
		// // 此处设置开发者获取到的方向信息，顺时针0-360
		// .direction(100).latitude(location.getLatitude())
		// .longitude(location.getLongitude()).build();
		// mBaiduMap.setMyLocationData(locData);
		// if (isFirstLoc) {
		// isFirstLoc = false;
		// LatLng ll = new LatLng(location.getLatitude(),
		// location.getLongitude());
		// MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
		// mBaiduMap.animateMapStatus(u);
		// }
		// }
	}

	@Override
	protected void onPause() {
		super.onPause();
		// activity 暂停时同时暂停地图控件
		mMapView.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// activity 恢复时同时恢复地图控件
		mMapView.onResume();
	}

	@Override
	protected void onDestroy() {
		mApplication.removeOnLocationResultListener(this);

		super.onDestroy();
		// activity 销毁时同时销毁地图控件
		// mMapView.onDestroy();
	}

	/**
	 * 搜索结果
	 */
	public void onGetPoiDetailResult(PoiDetailResult arg0) {
	}

	@Override
	public void onGetPoiResult(PoiResult result) {
		if (result == null
				|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND
				|| result.getAllPoi() == null) {
			list_key.clear();
			notifyDataSetChanged(mMyAdapter_search);
			return;
		} else {
			list_key.clear();
			tv_loading.setText(getString(R.string.tv_loading));
			listview.setVisibility(View.VISIBLE);
			List<PoiInfo> listpoi = result.getAllPoi();
			for (int i = listpoi.size() - 1; i >= 0; i--) {
				if (listpoi.get(i).location == null)
					listpoi.remove(i);
			}
			if (is_detail.equals(Value.CITY_DETAIL)) {// 显示具体信息，则值显示一个
				list_key.add(listpoi.get(0));
			} else {
				list_key.addAll(listpoi);
			}

			notifyDataSetChanged(mMyAdapter_search);
		}

	}

	/**
	 * 地理编码结果（地理到经纬度的结果）
	 */
	public void onGetGeoCodeResult(GeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			list_geo.clear();
			notifyDataSetChanged(mMyAdapter_geocoder);
			return;
		}

	}

	/**
	 * 地理编码结果（经纬度到地址的结果）
	 */
	public void onGetReverseGeoCodeResult(final ReverseGeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR
				|| result.getPoiList() == null) {
			list_geo.clear();
			notifyDataSetChanged(mMyAdapter_geocoder);
			return;
		}
		myposition = result;
		tv_loading.setText(getString(R.string.tv_loading));
		listview.setVisibility(View.VISIBLE);
		List<PoiInfo> listpoi = result.getPoiList();
		for (int i = listpoi.size() - 1; i >= 0; i--) {
			if (listpoi.get(i).location == null)
				listpoi.remove(i);
		}
		list_geo.clear();
		PoiInfo poiinfo = new PoiInfo();
		poiinfo.name = result.getAddress().replace(
				myposition.getAddressDetail().province
						+ myposition.getAddressDetail().city, "");
		poiinfo.address = result.getAddress();
		poiinfo.city = result.getAddressDetail().city;
		poiinfo.location = result.getLocation();
		list_geo.add(poiinfo);
		list_geo.addAll(listpoi);
		for (int i = 0; i < list_geo.size(); i++) {
			list_geo.get(i).city = result.getAddressDetail().city;
		}
		notifyDataSetChanged(mMyAdapter_geocoder);
		tv_myposition.setText(result.getAddress());
		if (!isCityInformation(result.getAddressDetail().city.trim())) {
			myposition = null;
			list_geo.clear();

		}
		Animation anim = AnimationUtils.loadAnimation(this, R.anim.mapid);
		icon_mapid.startAnimation(anim);
		anim.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				Animation anim = AnimationUtils.loadAnimation(
						EditAddressActivity.this, R.anim.dialog_in);
				tv_myposition.startAnimation(anim);
				tv_myposition.setVisibility(View.VISIBLE);
				tv_myposition.setText(result.getAddress());
				if (!isCityInformation(result.getAddressDetail().city.trim())) {
					tv_myposition.setText(getString(R.string.no_incity));
				}
				if (!isInCity) {
					// 判断拼车类型，是否移除该城市
					String location_city = result.getAddressDetail().city
							.trim();
					String in_city = tv_city.getText().toString();
					if (!ToCity.getCityName(in_city).equals(
							ToCity.getCityName(location_city))) {
						layout_switch_city.setVisibility(View.VISIBLE);
						tv_myposition.setOnClickListener(null);
						tv_myposition.setText(String.format(
								getString(R.string.remove_position),
								ToCity.getCityName(in_city)));
					} else {
						layout_switch_city.setVisibility(View.GONE);
						tv_myposition
								.setOnClickListener(EditAddressActivity.this);
					}

				}
			}
		});
	}

	@Override
	public void afterTextChanged(Editable s) {
		if (!s.toString().isEmpty()) {
			if (isNoCity()) {
				if (isInCity && !list_incity_cn.isEmpty()) {

				} else {
					showCity();
				}
			} else {
				notifyDataSetChanged(mMyAdapter_search);
				iv_delete.setVisibility(View.VISIBLE);
				tv_loading.setVisibility(View.VISIBLE);
				tv_loading.setText(getString(R.string.tv_loading));
				
			}

		} else {
			iv_delete.setVisibility(View.GONE);
			if(type!=TYPE_GEOCODER){
				notifyDataSetChanged(mMyAdapter_collect);
			}else{
				notifyDataSetChanged(mMyAdapter_geocoder);
			}
		}
		onCityKeySearch(s.toString(), false);

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_cancel:
		case R.id.iv_left:
			// if (layout_search.getVisibility() == View.VISIBLE) {
			// if (intentType == AddressMsg.ADDRESS_START)
			// hideEditText();
			// else
			// onfinish();
			// } else {
			// onfinish();
			// }
			onfinish();
			break;
		case R.id.layout_city:
			if (isInCity && !list_incity_cn.isEmpty()) {

			} else {
				if (type != TYPE_SEARCH) {
					showEditText(false);
					showCity();
				} else {
					showCity();
				}
			}

			break;
		// case R.id.tv_edit:
		// showEditText(true);
		// break;
		case R.id.iv_delete:
			et_edit.setText("");
			break;
		case R.id.iv_city_delete:
			et_city.setText("");
			break;
		case R.id.tv_myposition:
			if (myposition != null) {
				Bundle bundle = new Bundle();
				bundle.putString(
						AddressMsg.extra_address_name,
						myposition.getAddressDetail().city
								+ " "
								+ myposition
										.getAddress()
										.replace(
												myposition.getAddressDetail().province
														+ myposition
																.getAddressDetail().city,
												""));
				// 我的位置，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city,
						myposition.getAddressDetail().city);
				bundle.putString(AddressMsg.extra_address_address,
						myposition.getAddress());
				bundle.putDouble(AddressMsg.extra_address_latitude,
						myposition.getLocation().latitude);
				bundle.putDouble(AddressMsg.extra_address_longitude,
						myposition.getLocation().longitude);
				bundle.putInt(AddressMsg.extra_address_point_id,point_id);
				Intent intent = new Intent();
				intent.putExtras(bundle);
				setResult(resultCode, intent);
				onfinish();
			}
			break;
		case R.id.et_edit:
			if (type != TYPE_SEARCH) {
				showEditText(true);
				hideCity();
			} else {
				if (tv_city.getText().toString() != null
						&& !tv_city.getText().toString().equals("")
						&& !tv_city.getText().toString()
								.equals(getString(R.string.default_city))
						&& !tv_city.getText().toString().equals("null")) {
					hideCity();
				} else {
					setEditTextCityFocusable();
					ToastUtil.showToast(context, R.string.choice_city);
				}
			}

			break;
		case R.id.iv_locate:
			setCenterPoint(mApplication.latitude, mApplication.longitude, 16);
			break;
		default:
			super.onClick(v);
			break;
		}

	}

	/**
	 * 判断是否是具体信息搜索，如厦门北站
	 */
	public void onIsSearchDetail(String is_detail, String city) {
		tv_city.setText(city);
		// 具体信息，如厦门北站
		if (is_detail != null && is_detail.equals(Value.CITY_DETAIL)) {
			et_edit.setText(et_edit.getText().toString());
			et_edit.setSelection(et_edit.getText().length());
			et_edit.setHint(city);
			et_edit.setEnabled(false);
			onCityKeySearch("", true);
			iv_delete.setVisibility(View.VISIBLE);
			tv_loading.setVisibility(View.VISIBLE);
			tv_loading.setText(getString(R.string.tv_loading));
			iv_delete.setVisibility(View.GONE);
			hideInput();
		} else {
			showInput();
			et_edit.setEnabled(true);
			readAllDB_address();
			et_edit.setHint(getResources().getString(R.string.adr_hint));
			iv_delete.setVisibility(View.GONE);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
		if (arg0.getAdapter() == mMyAdapter_geocoder) {
			Bundle bundle = new Bundle();
			String name = list_geo.get(position).name;
			String city = list_geo.get(position).city;
			String name_detail = ToCity.getCityDetail(this, name);
			if (name_detail != null) {
				bundle.putString(AddressMsg.extra_address_name, name_detail);
				// 地理编码信息，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city, name_detail);
			} else {
				bundle.putString(AddressMsg.extra_address_name, city + " "
						+ name);
				// 地理编码信息，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city, city);
			}

			bundle.putString(AddressMsg.extra_address_address,
					list_geo.get(position).address);
			bundle.putDouble(AddressMsg.extra_address_latitude,
					list_geo.get(position).location.latitude);
			bundle.putDouble(AddressMsg.extra_address_longitude,
					list_geo.get(position).location.longitude);
			bundle.putInt(AddressMsg.extra_address_point_id,point_id);
			Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();
		} else if (arg0.getAdapter() == mMyAdapter_search) {
			Bundle bundle = new Bundle();
			// bundle.putString(AddressMsg.extra_address_name,
			// list_key.get(position).city + " "
			// + list_key.get(position).name);
			// 搜索去城市，则取左上角的城市名
			// bundle.putString(AddressMsg.extra_address_city,
			// list_key.get(position).city);
			String name = list_key.get(position).name;
			String city = list_key.get(position).city;
			String name_detail = ToCity.getCityDetail(this, name);
			if (name_detail != null) {
				bundle.putString(AddressMsg.extra_address_name, name_detail);
				// 地理编码信息，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city, name_detail);
			} else {

				if (is_detail.equals(Value.CITY_DETAIL)) {// 显示具体信息，则值显示一个
					bundle.putString(AddressMsg.extra_address_name, tv_city
							.getText().toString());
					bundle.putString(AddressMsg.extra_address_city, tv_city
							.getText().toString());
				} else {
					bundle.putString(
							AddressMsg.extra_address_name,
							tv_city.getText().toString() + " "
									+ list_key.get(position).name);
					bundle.putString(AddressMsg.extra_address_city, tv_city
							.getText().toString());
				}
			}

			bundle.putString(AddressMsg.extra_address_address,
					list_key.get(position).address);
			bundle.putDouble(AddressMsg.extra_address_latitude,
					list_key.get(position).location.latitude);
			bundle.putDouble(AddressMsg.extra_address_longitude,
					list_key.get(position).location.longitude);
			bundle.putInt(AddressMsg.extra_address_point_id,point_id);
			Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();
		} else if (arg0.getAdapter() == mMyAdapter_collect) {
			Bundle bundle = new Bundle();
			bundle.putString(AddressMsg.extra_address_name,
					list_collect.get(position).get(DBcolumns.ADDRESS_NAME));
			// 历史记录城市则取数据库，没有则取空
			bundle.putString(AddressMsg.extra_address_city,
					list_collect.get(position).get(DBcolumns.ADDRESS_CITY));
			bundle.putString(AddressMsg.extra_address_address, list_collect
					.get(position).get(DBcolumns.ADDRESS_ADDRESS));
			bundle.putDouble(
					AddressMsg.extra_address_latitude,
					Double.parseDouble(list_collect.get(position).get(
							DBcolumns.ADDRESS_LATITUDE)));
			bundle.putDouble(
					AddressMsg.extra_address_longitude,
					Double.parseDouble(list_collect.get(position).get(
							DBcolumns.ADDRESS_LONGITUDE)));
			bundle.putInt(AddressMsg.extra_address_point_id,point_id);
			Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();
		}

	}

	@Override
	public void onLocationResult(BDLocation location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		initDefaultLocation(location);
		onGeoCoder(latitude, longitude);
		// 只定位一次
		mApplication.removeOnLocationResultListener(this);
		String city = location.getCity();
		if (city != null && isLocationCity) {
		}
	}

	@Override
	public void onLocationResult(ReverseGeoCodeResult result) {
		latitude = result.getLocation().latitude;
		longitude = result.getLocation().longitude;
		initDefaultLocation(result);
		onGeoCoder(latitude, longitude);
		// 只定位一次
		mApplication.removeOnLocationResultListener(this);
		String city = result.getAddressDetail().city;
		if (city != null && isLocationCity) {
		}
	}

	@Override
	public void onLocationFail(boolean isnet) {
		// TODO Auto-generated method stub

	}

	public void showEditText(final boolean isInput) {
		int time=0;
		if (intentType == AddressMsg.ADDRESS_START_MAIN) {
			LayoutTransition lt = new LayoutTransition();
			lt.disableTransitionType(LayoutTransition.DISAPPEARING);
			layout_listview.setLayoutTransition(lt);
			time=800;
		}
		map_view.setVisibility(View.GONE);
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if (et_edit.getText().toString().equals("")) {
					notifyDataSetChanged(mMyAdapter_collect);
				} else {
					notifyDataSetChanged(mMyAdapter_search);
				}
				// tv_edit.setVisibility(View.GONE);
				et_edit.setFocusable(true);
				if (isInput) {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}, time);
		
	}

	public void hideEditText() {
		map_view.setVisibility(View.VISIBLE);
		// tv_edit.setVisibility(View.VISIBLE);
	}

	public void showCity() {
		if (!isInCity) {
			layout_city.setVisibility(View.GONE);
			layout_city_search.setVisibility(View.VISIBLE);
			citydragLayout.setType(intentType);
			citydragLayout.setStartName(address_name);
			citydragLayout.setIsInCity(isInCity);

			citydragLayout.setaddTextChangedListener(et_city, iv_city_delete);
			setEditTextCityFocusable();
			citydragLayout.maximize();
		} else {
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					hideCity();
				}
			}, 50);

		}
	}

	public void hideCity() {
		layout_city.setVisibility(View.VISIBLE);
		layout_city_search.setVisibility(View.GONE);
		setEditTextSearchFocusable();
		citydragLayout.minimize();
	}

	/**
	 * 设置城市搜索为焦点
	 */
	public void setEditTextCityFocusable() {
		et_edit.setText("");
		et_edit.setFocusable(false);
		et_city.setFocusable(true);
		et_city.setFocusableInTouchMode(true);
		et_city.requestFocus();
		et_city.requestFocusFromTouch();
		// showInput();

	}

	/**
	 * 设置搜索框为焦点
	 */
	public void setEditTextSearchFocusable() {
		et_city.setText("");
		et_city.setFocusable(false);
		et_edit.setFocusable(true);
		et_edit.setFocusableInTouchMode(true);
		et_edit.requestFocus();
		et_edit.requestFocusFromTouch();
		showInput();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			// if (layout_search.getVisibility() == View.VISIBLE) {
			// if (intentType == AddressMsg.ADDRESS_START)
			// hideEditText();
			// else
			// onfinish();
			// } else {
			// onfinish();
			// }
			onfinish();
			return true;

		}
		return false;
	}

	public void notifyDataSetChanged(BaseAdapter adapter) {
		onisShowNodata(adapter);
		tv_loading.setVisibility(View.GONE);
	}

	public void onisShowNodata(BaseAdapter adapter) {
		if (adapter == mMyAdapter_search) {
			type = TYPE_SEARCH;
			listview.setAdapter(mMyAdapter_search);
			adapter.notifyDataSetChanged();
		} else if (adapter == mMyAdapter_geocoder) {
			type = TYPE_GEOCODER;
			listview.setAdapter(mMyAdapter_geocoder);
			adapter.notifyDataSetChanged();
		} else if (adapter == mMyAdapter_collect) {
			type = TYPE_COLLECT;
			listview.setAdapter(mMyAdapter_collect);
			adapter.notifyDataSetChanged();
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_SELETE_CITY:
				String s = (String) msg.obj;
				String city = s.split(split)[0];
				try {
					is_detail = s.split(split)[1];
				} catch (Exception e) {
				}
				onIsSearchDetail(is_detail, city);
				break;
			}
		}
	};

	/**
	 * 判断是否开启获取城市。
	 */
	public boolean isCityInformation(String city) {
		city = ToCity.getCityName(city);
		boolean isExist = false;
		if (isInCity && list_incity_cn != null && !list_incity_cn.isEmpty()) {
			for (int i = 0; i < list_incity_cn.size(); i++) {
				String city2 = list_incity_cn.get(i).trim();
				city2 = ToCity.getCityName(city2);
				if (city2.equals(city)) {
					String location_city = mApplication.loctionCity;
					location_city = ToCity.getCityName(location_city);
					if (city.equals(location_city)) {
						isExist = true;
					}

				}
			}

		} else {
			if (isInCity) {
				isExist = false;
			} else {
				isExist = true;
			}

		}
		return isExist;
	}

	/**
	 * 判断左上角有没有城市，true,没城市
	 */
	public boolean isNoCity() {
		boolean isnocity = false;
		if (tv_city.getText().toString().equals("null")
				|| tv_city.getText().toString().equals("")
				|| tv_city.getText().toString()
						.equals(getString(R.string.default_city))) {
			isnocity = true;
		}
		return isnocity;
	}

	/**
	 * 设置中心点位置
	 */
	public void setCenterPoint(double lat, double lng, final int zoom) {
		LatLng cenpt = new LatLng(lat, lng);
		MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).build();
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
				.newMapStatus(mMapStatus);
		mBaiduMap.animateMapStatus(mMapStatusUpdate);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(zoom);
				mBaiduMap.animateMapStatus(u);
			}
		}, 500);

	}

	@Override
	public void onDragViewStatus(boolean isOpen) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClickCity(String city, String is_detail) {
		is_detail = Value.CITY_NODETAIL;
		setEditTextSearchFocusable();
		et_city.setText("");
		if (city != null && is_detail != null) {
			hideCity();
			this.is_detail = is_detail;
			onIsSearchDetail(is_detail, city);
		}
	}
}
